Component({
    /**
     * 组件的属性列表
     */
    properties: {
        visible: {
            type: Boolean,
            value: false,
            observer: function (newVal) {
                if (newVal) {
                    this._showAnimation();
                    this.startCountdown();
                } else {
                    this._hideAnimation();
                    this.stopCountdown();
                }
            }
        },
        rankingTitle: {
            type: String,
            value: '排行榜'
        },
        rankingData: {
            type: Array,
            value: [],
            observer: function (newVal) {
                if (newVal && newVal.length > 0) {
                    this._processRankingData(newVal);
                } else {
                    this.setData({
                        podiumList: [],
                        rankingList: [],
                        noData: true
                    });
                }
            }
        },
        pageIndex: {
            type: Number,
            value: 1
        },
        hasMore: {
            type: Boolean,
            value: true
        },
        endTime: {
            type: Number,
            value: 0, // 结束时间戳
            observer: function (newVal) {
                if (newVal > 0) {
                    this.calculateCountdown(newVal);
                }
            }
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        animationData: {},
        podiumList: [],
        rankingList: [],
        isLoading: false,
        hasMore: true,
        noData: false,
        countdown: {
            hours: '12',
            minutes: '00',
            seconds: '00'
        },
        countdownTimer: null,
        showUserDetail: false,
        currentUser: null,
        pop_height:700,
    },
    

    lifetimes: {
      attached() {
        const sys = wx.getSystemInfoSync();
        const sysbar = wx.getMenuButtonBoundingClientRect();
        console.log('系统信息:', sys);
        console.log('胶囊按钮信息:', sysbar);
    
        const pop_height = sys.windowHeight - sysbar.bottom

        this.setData({
          pop_height,
        });
      }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 处理排行榜数据
         */
        _processRankingData(data) {
            if (!data || data.length === 0) {
                this.setData({
                    podiumList: [],
                    rankingList: [],
                    noData: true
                });
                return;
            }

            let podiumList = [];
            let rankingList = [];

            // 前三名为领奖台数据
            if (data.length > 0) {
                podiumList = data.slice(0, Math.min(3, data.length));
            }

            // 第四名开始为排行榜数据 - 不做限制，允许全部显示
            if (data.length > 3) {
                rankingList = data.slice(3);
            }

            // 获取当前用户ID并检查排名
            const currentUserId = wx.getStorageSync('userId');
            let myRank = null;

            if (currentUserId) {
                // 在完整数据中查找用户位置
                const index = data.findIndex(item => item.id === currentUserId);
                if (index !== -1) {
                    myRank = index + 1; // 实际排名从1开始
                }
            }

            this.setData({
                podiumList,
                rankingList,
                noData: data.length === 0,
                hasMore: this.properties.hasMore,
                myRank // 添加用户排名到数据中
            });
        },

        /**
         * 打开弹窗
         */
        _showAnimation() {
            const animation = wx.createAnimation({
                duration: 300,
                timingFunction: 'ease',
            });

            animation.translateY(0).opacity(1).step();

            this.setData({
                animationData: animation.export()
            });
        },

        /**
         * 关闭弹窗
         */
        _hideAnimation() {
            const animation = wx.createAnimation({
                duration: 300,
                timingFunction: 'ease',
            });

            animation.translateY('100%').opacity(0).step();

            this.setData({
                animationData: animation.export()
            });
        },

        /**
         * 关闭弹窗
         */
        onClose() {
            this.triggerEvent('close');
        },

        /**
         * 加载更多
         */
        loadMore() {
            if (this.data.isLoading || !this.data.hasMore) {
                return;
            }

            this.setData({
                isLoading: true
            });

            // 触发加载更多事件
            this.triggerEvent('loadmore', {
                pageIndex: this.properties.pageIndex + 1
            });

            // 模拟加载结束
            setTimeout(() => {
                this.setData({
                    isLoading: false
                });
            }, 1000);
        },

        /**
         * 点击用户头像
         */
        onUserTap(e) {
            const { index, type } = e.currentTarget.dataset;
            let userData = null;

            if (type === 'podium') {
                if (this.data.podiumList.length > index) {
                    userData = this.data.podiumList[index];
                }
            } else if (type === 'ranking') {
                if (this.data.rankingList.length > index) {
                    userData = this.data.rankingList[index];
                }
            }

            if (userData) {
                this.setData({
                    showUserDetail: true,
                    currentUser: userData
                });
            }
        },

        /**
         * 关闭用户详情弹窗
         */
        closeUserDetail() {
            this.setData({
                showUserDetail: false,
                currentUser: null
            });
        },

        /**
         * 开始倒计时
         */
        startCountdown() {
            // 如果没有设置结束时间，默认12小时
            if (this.properties.endTime <= 0) {
                const endTime = Date.now() + 12 * 60 * 60 * 1000;
                this.calculateCountdown(endTime);
            } else {
                this.calculateCountdown(this.properties.endTime);
            }

            // 每秒更新一次
            this.data.countdownTimer = setInterval(() => {
                if (this.properties.endTime <= 0) {
                    const endTime = Date.now() + 12 * 60 * 60 * 1000;
                    this.calculateCountdown(endTime);
                } else {
                    this.calculateCountdown(this.properties.endTime);
                }
            }, 1000);
        },

        /**
         * 停止倒计时
         */
        stopCountdown() {
            if (this.data.countdownTimer) {
                clearInterval(this.data.countdownTimer);
                this.data.countdownTimer = null;
            }
        },

        /**
         * 计算倒计时
         */
        calculateCountdown(endTime) {
            const now = Date.now();
            let diff = Math.max(0, endTime - now);

            // 计算小时、分钟、秒
            const hours = Math.floor(diff / (1000 * 60 * 60));
            diff -= hours * 1000 * 60 * 60;
            const minutes = Math.floor(diff / (1000 * 60));
            diff -= minutes * 1000 * 60;
            const seconds = Math.floor(diff / 1000);

            // 格式化为两位数
            const formatNumber = n => {
                n = n.toString();
                return n[1] ? n : '0' + n;
            };

            this.setData({
                countdown: {
                    hours: formatNumber(hours),
                    minutes: formatNumber(minutes),
                    seconds: formatNumber(seconds)
                }
            });
        },

        /**
         * 显示奖品记录
         */
        showPrizeRecord() {
            this.triggerEvent('showprize');
        },

        /**
         * 阻止滑动穿透 - 只阻止蒙层的滑动穿透
         */
        preventTouchMove() {
            // 不做任何操作，允许滚动传递
            return false;
        }
    },

    /**
     * 组件生命周期函数-在组件实例被从页面节点树移除时执行
     */
    detached() {
        // 清理定时器
        this.stopCountdown();
    }
}) 